//
//  AppDelegate.m
//  ksjv2
//
//  Created by cnbizMedia on 14/12/16.
//  Copyright (c) 2014年 CnbizMedia. All rights reserved.
//

#import "AppDelegate.h"
#import "Util.h"
#import "MainTabBarController.h"
#import "SlideTableViewController.h"
#import "ADViewController.h"
#import "GuideViewController.h"
#import "ArticleViewController.h"
#import "WXApi.h"
#import <TencentOpenAPI/TencentOAuth.h>
#import "BaiduMobStat.h"
#import "SDURLCache.h"
#import "MobClick.h"
#import <AlipaySDK/AlipaySDK.h>

#define APP_KEY @"Szn3HlldKZOiaScMev73fG6V"
#define REPORT_ID @"5a38251b49"


#define UMSYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

#define SXSCREEN_W [UIScreen mainScreen].bounds.size.width

#define IosAppVersion [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]
#import "UMSocial.h"
#import "UMSocialQQHandler.h"
#import "UMSocialWechatHandler.h"
#import "UMessage.h"
@interface AppDelegate (){
    NSTimer *connectionTimer;
    BOOL done;
    ADViewController*adview;

    UInt64 oldTime;
    UInt64 nowTime;
    
    
 
}
@property (strong, nonatomic) IBOutlet UILabel *longitude;
@property (strong, nonatomic) IBOutlet UILabel *latitude;

@property (strong, nonatomic) IBOutlet UILabel *location;
@property (strong, nonatomic) CLLocationManager *locationManager;

@end

@implementation AppDelegate
@synthesize  BadgeArray,BadgeStr;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    SET_NAV_BAR;
    SET_STA_BAR;
    SET_TAB_BAR;
    
    [MobClick setLogEnabled:YES];
    
  
    
    // 判断定位操作是否被允许
    
    if([CLLocationManager locationServicesEnabled]) {
        
        self.locationManager = [[CLLocationManager alloc] init] ;
        
        self.locationManager.delegate = self;
        
    }else {
        
        //提示用户无法进行定位操作
        
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:
                                  
                                  @"提示" message:@"定位不成功 ,请确认开启定位" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        
        [alertView show];
        
    }
    
    // 开始定位
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    _locationManager.distanceFilter = 10;
    [_locationManager requestAlwaysAuthorization];//添加这句
    [self.locationManager startUpdatingLocation];
    
    
    
    //友盟集成测试
    Class cls = NSClassFromString(@"UMANUtil");
    SEL deviceIDSelector = @selector(openUDIDString);
    NSString *deviceID = nil;
    if(cls && [cls respondsToSelector:deviceIDSelector]){
        deviceID = [cls performSelector:deviceIDSelector];
    }
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:@{@"oid" : deviceID}
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:nil];
    
    NSLog(@"友盟集成测试%@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
    
    
    
    NSMutableDictionary*dic_m=[NSMutableDictionary dictionaryWithDictionary:[UserDefaults objectForKey:@"usDic"]];
    NSLog(@"dic_m ----%@",dic_m);

    NSMutableDictionary*dic_w=[NSMutableDictionary dictionaryWithDictionary:[UserDefaults objectForKey:@"user"]];
    NSLog(@"dic_w ----%@",dic_w);
    
    
    #define IS_IPHONE5 (([[UIScreen mainScreen] bounds].size.height == 568) ? YES : NO)
    
    #define IS_IPhone6 (667 == [[UIScreen mainScreen] bounds].size.height ? YES : NO)
    
    #define IS_IPhone6plus (736 == [[UIScreen mainScreen] bounds].size.height ? YES : NO)
    
    if ([[UIScreen mainScreen] bounds].size.height == 568) {
        [UserDefaults setObject:@"iphone5" forKey:@"iphoneTheHight"];
    }
    if ([[UIScreen mainScreen] bounds].size.height == 667) {
        [UserDefaults setObject:@"iphone6" forKey:@"iphoneTheHight"];
    }
    if ([[UIScreen mainScreen] bounds].size.height == 736) {
        [UserDefaults setObject:@"iphone6p" forKey:@"iphoneTheHight"];
    }
    
//    NSDictionary *abcabc = [orderDic objectForKey:@"trade_sn"];
//    NSLog(@"");
    
    self.BadgeArray=[[NSMutableArray alloc]init];
//    self.BadgeStr=@"5";
    
    
    //判断是不是要放置新春版
    NSString *newOldYear = [UserDefaults objectForKey:@"NewYear" ];
    if ([newOldYear isEqualToString:@"NewYear"]) {
        //状态栏的文字颜色换成白色
//        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    }
    else{
//        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    
    }
    
    ///用户引导
    UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
     NSLog(@"UserDefaults %@",UserDefaults);
    
    NSLog(@"launchOptions %@",launchOptions);
    
    
    [UMSocialData setAppKey:@"52afe78656240b558f00f76b"];//友盟第三方
    [UMSocialQQHandler setQQWithAppId:@"100578511" appKey:@"JrU791nY80h6SqTX" url:@"http://www.kanshangjie.com"];
    //设置微信AppId、appSecret，分享url
    [UMSocialWechatHandler setWXAppId:WEIXIN_APP_KEY appSecret:WEIXIN_App_Secret url:@"http://www.kanshangjie.com"];
    
    
    
    //向微信注册 支付
    [WXApi registerApp:APP_ID withDescription:@"demo 2.0"];
    
    if ([UserDefaults objectForKey:@"First"]) {
 
       
        
        ADViewController*ad=[story instantiateViewControllerWithIdentifier:@"ADViewController"];
        adview=ad;
        [application setApplicationIconBadgeNumber:0];//设置应用图标的消息数
        
        [ad MainVC];
//        launchOptions = @{@"type":@"url",@"content":@"http://www.baidu.com/"};
                if (launchOptions) {


            //NSString*key=[NSString stringWithFormat:@"%@",[launchOptions allKeys][0]];
            //NSDictionary*dic=launchOptions[key];
            
            ad.Push_dic = launchOptions;
            //[self performSelector:@selector(pushdata:) withObject:dic afterDelay:7];
        }        
    [self.window setRootViewController:ad];
            
    }else{
        [UserDefaults setObject:@"First" forKey:@"First"];
        GuideViewController*guide=[story instantiateViewControllerWithIdentifier:@"GuideViewController"];
        [self.window setRootViewController:guide];
    }
    //分享、三方登录
    [BDSocialShareSDK_Internal registerApiKey:APP_KEY supportSharePlatforms:
  @[kBD_SOCIAL_SHARE_PLATFORM_WEIXIN_SESSION,
    kBD_SOCIAL_SHARE_PLATFORM_WEIXIN_TIMELINE,
    kBD_SOCIAL_SHARE_PLATFORM_SINAWEIBO,
    kBD_SOCIAL_SHARE_PLATFORM_QQWEIBO,
    kBD_SOCIAL_SHARE_PLATFORM_QQFRIEND,
    kBD_SOCIAL_SHARE_PLATFORM_EMAIL,
    kBD_SOCIAL_SHARE_PLATFORM_SMS,
    kBD_SOCIAL_SHARE_PLATFORM_COPY]];

    [BDSocialShareSDK_Internal registerQQApp:QQ_APP_KEY enableSSO:YES];
    [BDSocialShareSDK_Internal registerSinaWeiboApp:KEY_SINA_WEIBO];
    [BDSocialShareSDK_Internal setAnimationTime:0.25f];
    [BDSocialShareSDK_Internal registerWXApp:WEIXIN_APP_KEY];
    //向微信注册
//    [WXApi registerApp:WEIXIN_APP_KEY withDescription:@"ksjv2.0"];
    //推送
    
     // 开发测试环境             BPushModeDevelopment,
    // AppStore 上线环境        BPushModeProduction,
    [BPush registerChannel:launchOptions apiKey:@"Szn3HlldKZOiaScMev73fG6V" pushMode:BPushModeProduction isDebug:YES];
//    [BPush setupChannel:launchOptions];
    [BPush setDelegate:self];
    [BPush bindChannel];
    
    [application setApplicationIconBadgeNumber:0];//设置应用图标的消息数
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:myTypes categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];

    }else
    {
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
    }
    
    BaiduMobStat* statTracker = [BaiduMobStat defaultStat];
    [statTracker startWithAppId:@"5a38251b49"];
    statTracker.enableExceptionLog = YES; // 是否允许截获并发送崩溃信息，请设置YES或者NO
//    statTracker.channelId = @"App Store";//设置您的app的发布渠道
    statTracker.logStrategy = BaiduMobStatLogStrategyAppLaunch;//根据开发者设定的发送策略,发送日志
    statTracker.logSendInterval = 1;  //为1时表示发送日志的时间间隔为1小时,当logStrategy设置为BaiduMobStatLogStrategyCustom时生效
    statTracker.logSendWifiOnly = YES; //是否仅在WIfi情况下发送日志数据
    statTracker.sessionResumeInterval = 10;//设置应用进入后台再回到前台为同一次session的间隔时间[0~600s],超过600s则设为600s，默认为30s
    statTracker.shortAppVersion  = IosAppVersion; //参数为NSString * 类型,自定义app版本信息，如果不设置，默认从CFBundleVersion里取
    statTracker.enableDebugOn = YES; //调试的时候打开，会有log打印，发布时候关闭
    
    [MobClick startWithAppkey:@"52afe78656240b558f00f76b" reportPolicy:REALTIME channelId:@"App Store"];
//    [MobClick checkUpdate];
//    [MobClick startWithAppkey:@"561f803b67e58e01e80001fc" reportPolicy:REALTIME channelId:@"App Store"];

//    我自己的账号的appkey，用来测试用 561f803b67e58e01e80001fc
    
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSLog(@"--version-- %@",version);
    [MobClick setAppVersion:version];
    
//    SDURLCache *cache = [[SDURLCache alloc] initWithMemoryCapacity:30 * 1024 * 1024   // 30MB
//                                                      diskCapacity:1024 * 1024 * 1024 // 1024MB
//                                                          diskPath:[SDURLCache defaultCachePath]
//                                                enableForIOS5AndUp:YES];
//    [cache setIgnoreMemoryOnlyStoragePolicy:NO];
//    [NSURLCache setSharedURLCache:cache];
    
    
    
    //set AppKey and AppSecret  52afe78656240b558f00f76b
    [UMessage startWithAppkey:@"52afe78656240b558f00f76b" launchOptions:launchOptions];
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE80_
    if(UMSYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0"))
    {
        //register remoteNotification types （iOS 8.0及其以上版本）
        UIMutableUserNotificationAction *action1 = [[UIMutableUserNotificationAction alloc] init];
        action1.identifier = @"action1_identifier";
        action1.title=@"Accept";
        action1.activationMode = UIUserNotificationActivationModeForeground;//当点击的时候启动程序
        
        UIMutableUserNotificationAction *action2 = [[UIMutableUserNotificationAction alloc] init];  //第二按钮
        action2.identifier = @"action2_identifier";
        action2.title=@"Reject";
        action2.activationMode = UIUserNotificationActivationModeBackground;//当点击的时候不启动程序，在后台处理
        action2.authenticationRequired = YES;//需要解锁才能处理，如果action.activationMode = UIUserNotificationActivationModeForeground;则这个属性被忽略；
        action2.destructive = YES;
        
        UIMutableUserNotificationCategory *categorys = [[UIMutableUserNotificationCategory alloc] init];
        categorys.identifier = @"category1";//这组动作的唯一标示
        [categorys setActions:@[action1,action2] forContext:(UIUserNotificationActionContextDefault)];
        
        UIUserNotificationSettings *userSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert
                                                                                     categories:[NSSet setWithObject:categorys]];
        [UMessage registerRemoteNotificationAndUserNotificationSettings:userSettings];
        
    } else{
        //register remoteNotification types (iOS 8.0以下)
        [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
         |UIRemoteNotificationTypeSound
         |UIRemoteNotificationTypeAlert];
    }
#else
    
    //register remoteNotification types (iOS 8.0以下)
    [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
     |UIRemoteNotificationTypeSound
     |UIRemoteNotificationTypeAlert];
    
#endif
    //for log
    [UMessage setLogEnabled:YES];
    
    return YES;
}
- (NSString *)cachePath
{
    NSArray *paths =
    NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString* documentsDirectory = [paths objectAtIndex:0];
    NSString* diskCachePath = [documentsDirectory stringByAppendingPathComponent:@"com.cnbizmedia.kanshangjie"];
    NSLog(@"diskCachePath = %@", diskCachePath);
    
    return diskCachePath;
}
-(void)pushdata:(NSDictionary*)dic{
    if ([[dic objectForKey:@"type"] isEqualToString:@"url"]) {
        adview.Push_dic=dic;
        
    }else if ([[dic objectForKey:@"type"] isEqualToString:@"user_point"]){

        NSArray*array=[dic[@"content"] componentsSeparatedByString:@","];
        NSMutableDictionary*dic_m=[NSMutableDictionary dictionaryWithDictionary:[UserDefaults objectForKey:@"user"]];
        [dic_m setObject:array[2] forKey:@"point"];
        [UserDefaults setObject:dic_m forKey:@"user"];
        NSString*str=[NSString stringWithFormat:@"获得积分+%@",array[1]];
        [SVProgressHUD showSuccessWithStatus:str];
    }else if ([[dic objectForKey:@"type"] isEqualToString:@"view"]){
        
    }
}
-(void)onMethod:(NSString *)method response:(NSDictionary *)data{
    if ([method isEqualToString:@"bind"]) {
    NSDictionary*dic=data;
        NSLog(@"bind__%@",dic);
    [UserDefaults setObject:[NSString stringWithFormat:@"%@,%@",dic[@"user_id"],dic[@"channel_id"]] forKey:@"baiduid"];
    }
}
-(void)timerFired:(NSTimer *)timer{
    done=YES;
}


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{

    NSLog(@"tuishon %@userInfo",userInfo);
    if ([[userInfo objectForKey:@"type"] isEqualToString:@"url"]) {
        adview.Push_dic=userInfo;
        
    }else if ([[userInfo objectForKey:@"type"] isEqualToString:@"user_point"]){
        
        NSArray*array=[userInfo[@"content"] componentsSeparatedByString:@","];
        NSMutableDictionary*dic_m=[NSMutableDictionary dictionaryWithDictionary:[UserDefaults objectForKey:@"user"]];
        [dic_m setObject:array[2] forKey:@"point"];
        [UserDefaults setObject:dic_m forKey:@"user"];
        NSString*str=[NSString stringWithFormat:@"获得积分+%@",array[1]];
        [SVProgressHUD showSuccessWithStatus:str];
    }else if ([[userInfo objectForKey:@"type"] isEqualToString:@"view"]){
        
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:INNER_NOTIFICATION object:nil userInfo:userInfo];
    [application setApplicationIconBadgeNumber:0];
    
    [BPush handleNotification:userInfo];
    
     [UMessage didReceiveRemoteNotification:userInfo];
}

- (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    
    
    return YES;
}
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    //register to receive notifications
    [application registerForRemoteNotifications];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSLog(@"test:%@",deviceToken);
    [BPush registerDeviceToken: deviceToken];
    NSString *pushToken = [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<" withString:@""] stringByReplacingOccurrencesOfString:@">" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""] ;
    [UserDefaults setValue:pushToken forKey:@"X-Device-Token"];
    
    [UMessage registerDeviceToken:deviceToken];   //通知推送  Device Token 下面这个
    
    
    NSLog(@"通知推送 == %@",[[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]                  stringByReplacingOccurrencesOfString: @">" withString: @""]                 stringByReplacingOccurrencesOfString: @" " withString: @""]);

}
- (void)applicationWillResignActive:(UIApplication *)application {

    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {

    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    
    
    oldTime = [[NSDate date] timeIntervalSince1970] ;//*1000是毫秒，否则是秒
    NSLog(@"oldTime  == %llu",oldTime);
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {

    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
    nowTime = [[NSDate date] timeIntervalSince1970] ;//*1000是毫秒，否则是秒
    NSLog(@"nowTime  == %llu",nowTime);
    NSLog(@"nowTime - oldTime %llu",nowTime - oldTime);
    
    if (nowTime - oldTime > 600 && nowTime - oldTime < 100000) {
        
        oldTime = 0;
        
        UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
        ADViewController*ad=[story instantiateViewControllerWithIdentifier:@"ADViewController"];
        adview=ad;
        [application setApplicationIconBadgeNumber:0];//设置应用图标的消息数
//        [self.window removeFromSuperview];
//        self.window.rootViewController = ad;
//        [ad MainVC];
        
        
        
        
    }
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.cnbizmedia.ksjv2" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"ksjv2" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"ksjv2.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}


//以前分享的方法
//- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
//{
//    NSString*str_i=[sourceApplication  componentsSeparatedByString:@"."][1];
//    if ([str_i isEqualToString:@"tencent"]) {
//        NSString*xin=[sourceApplication  componentsSeparatedByString:@"."][2];
//        if ([xin isEqualToString:@"xin"]) {
//            return [WXApi handleOpenURL:url delegate:self.LonginVC];
//        }else{
//            return [TencentOAuth HandleOpenURL:url];
//        }
//        
//    }else{
//    NSLog(@"application__%@|,|url_%@|,|sourc_%@|,|ann_%@",application,url,sourceApplication,annotation);
//        return [BDSocialShareSDK_Internal handleOpenURL:url];
//    }
// }


- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
//    return [TencentOAuth HandleOpenURL:url];
    //这里根据URL来判断
    NSLog(@"url --++ %@",url);
    
    NSString *urlString = [NSString stringWithFormat:@"%@",url];
    NSString *aliString = @"alisdk";
    NSString *wxString  = @"wxcc";
    
    if([urlString rangeOfString:aliString].location !=NSNotFound)//_roaldSearchText
    {
        NSLog(@"alisdk");
    }
    
    if([urlString rangeOfString:wxString].location !=NSNotFound)//_roaldSearchText
    {
        NSLog(@"tencent");
        if ( [[UserDefaults objectForKey:@"wx"] isEqualToString:@"wxlogin"] ) {
            return  [UMSocialSnsService handleOpenURL:url];
        }
        
        if ([[UserDefaults objectForKey:@"wx"] isEqualToString:@"wxpay"]) {
            return  [WXApi handleOpenURL:url delegate:self];
        }
        
        
        return YES;
    }
  
    else{
    return  [UMSocialSnsService handleOpenURL:url];
    }
    
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}


- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    
    NSLog(@"url -- %@",url);
    NSLog(@"sourceApplication -- %@",sourceApplication);
    NSLog(@"annotation -- %@",annotation);
  
    
    
    NSString *urlString = [NSString stringWithFormat:@"%@",url];
    NSString *aliString = @"alisdk";
    NSString *wxString  = @"wxcc";
    
    if([urlString rangeOfString:aliString].location !=NSNotFound)//_roaldSearchText
    {
        NSLog(@"alisdk");
        
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result =++ %@",resultDic);
            
            if ([[resultDic objectForKey:@"success"]isEqualToString:@"true"]) {
                [UserDefaults setObject:@"yes" forKey:@"payEnd"];
            }
            else{
                [UserDefaults setObject:@"no" forKey:@"payEnd"];
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:@"getBackToUpView" object:self userInfo:nil ];
        }];
        return YES;
    }
    
    if([urlString rangeOfString:wxString].location !=NSNotFound)//_roaldSearchText
    {
        NSLog(@"tencent");
        if ( [[UserDefaults objectForKey:@"wx"] isEqualToString:@"wxlogin"] ) {
            return  [UMSocialSnsService handleOpenURL:url];
        }
        
        if ([[UserDefaults objectForKey:@"wx"] isEqualToString:@"wxpay"]) {
            //设置通知，显示微信支付后返回上一个界面
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"getBackToUpView" object:self userInfo:nil ];

            return  [WXApi handleOpenURL:url delegate:self];
        }
        
        
        return YES;
    }
    
    else{
        return  [UMSocialSnsService handleOpenURL:url];
    }
}


-(void) onResp:(BaseResp*)resp
{
    NSString *strMsg = [NSString stringWithFormat:@"errcode:%d", resp.errCode];
    NSString *strTitle;
    
    if([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        strTitle = [NSString stringWithFormat:@"发送媒体消息结果"];
    }
    if([resp isKindOfClass:[PayResp class]]){
        //支付返回结果，实际支付结果需要去微信服务器端查询
        strTitle = [NSString stringWithFormat:@"支付结果"];
        
        
        switch (resp.errCode) {
            case WXSuccess:
                strMsg = @"支付结果：成功！";
                NSLog(@"支付成功－%d", resp.errCode);//PaySuccess，retcode = 
                [UserDefaults setObject:@"yes" forKey:@"payEnd"];
                break;
                
            default:
                strMsg = [NSString stringWithFormat:@"支付结果：失败！retcode = %d, retstr = %@", resp.errCode,resp.errStr];
                NSLog(@"错误，retcode = %d, retstr = %@", resp.errCode,resp.errStr);
                
                [UserDefaults setObject:@"no" forKey:@"payEnd"];
                break;
        }
    }
    
    //设置通知，显示微信支付后返回上一个界面
    [[NSNotificationCenter defaultCenter] postNotificationName:@"getBackToUpView" object:self userInfo:nil ];
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
   
}






#pragma mark - CoreLocation Delegate

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations

{
    
    //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置，如果不想让其持续更新位置，则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
    
    CLLocation *currentLocation = [locations lastObject];
    
    // 获取当前所在的城市名
    
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    
    //根据经纬度反向地理编译出地址信息
    
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error)
     
     {
         
         if (array.count > 0)
             
         {
             
             CLPlacemark *placemark = [array objectAtIndex:0];
             
             //将获得的所有信息显示到label上
             
             NSLog(@"%@",placemark.name);
             
             //获取城市
             
             NSString *city = placemark.locality;
             
             if (!city) {
                 
                 //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                 
                 city = placemark.administrativeArea;
                 
             }
             
             //            self.cityName = city;
             NSLog(@"appdelegate获取的城市  %@",city);
             
             [UserDefaults setObject:city forKey:@"nowTheCity"];
         }
         
         else if (error == nil && [array count] == 0)
             
         {
             
             NSLog(@"No results were returned.");
             
         }
         
         else if (error != nil)
             
         {
             
             NSLog(@"An error occurred = %@", error);
             
         }
         
     }];
    
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
    
    [manager stopUpdatingLocation];
    
}

- (void)locationManager:(CLLocationManager *)manager

       didFailWithError:(NSError *)error {
    
    if (error.code == kCLErrorDenied) {
        
        // 提示用户出错原因，可按住Option键点击 KCLErrorDenied的查看更多出错信息，可打印error.code值查找原因所在
        
    }
    
}

@end
